<template>
  <div class="container">
    <!--搜索-->
    <div class="searchContent">
      <searchui :searchFormArr="searchFormArr" @searchParma="searchParma" :isAccording="isAccording"></searchui>
    </div>
    <div class="conBlock">
      <ul class="list_content" v-if="dataList.length > 0">
        <li class="list_item" v-for="(item, index) in dataList" :key="index">
          <el-row :gutter="24">
            <el-col :span="18">
              <dl class="list_item_l">
                <dt>
                  <span :class="item.run_sts == '3' ? 'finishedColor' : item.run_sts == '4' ? 'delColor' : ''" class="status">{{ item.run_sts == '1' ? '待开始' : item.run_sts == '2' ? '进行中' : item.run_sts == '3' ? '已结束' : item.run_sts == '4' ? '已终止' : '' }}</span>
                  <span class="rwName">任务名称【{{ item.title }}】</span>
                </dt>
                <el-row class="lineFirst">
                  <el-col :xs="18" :sm="18" :md="6" :lg="6" :xl="6"
                    ><dd>任务类型：<span>外呼</span></dd></el-col
                  >
                  <el-col :xs="18" :sm="18" :md="6" :lg="6" :xl="6"
                    ><dd>
                      任务完成情况：<span>{{ item.task_sts_num ? item.task_sts_num : '-' }}</span>
                    </dd></el-col
                  >
                  <el-col :xs="18" :sm="18" :md="6" :lg="6" :xl="6"
                    ><dd>
                      参与任务坐席数：<span>{{ item.site_num ? item.site_num : '-' }}</span>
                    </dd></el-col
                  >
                  <el-col :xs="18" :sm="18" :md="6" :lg="6" :xl="6"
                    ><dd>
                      数据接收人：<span>{{ item.user ? item.user : '-' }}</span>
                    </dd></el-col
                  >
                </el-row>
                <el-row>
                  <el-col :xs="18" :sm="18" :md="6" :lg="6" :xl="6"
                    ><dd>
                      创建时间：<span>{{ item.created_time ? item.created_time : '-' }}</span>
                    </dd></el-col
                  >
                  <el-col :xs="18" :sm="18" :md="6" :lg="6" :xl="6"
                    ><dd>
                      开始时间：<span>{{ item.start_time ? item.start_time : '-' }}</span>
                    </dd></el-col
                  >
                  <el-col :xs="18" :sm="18" :md="6" :lg="6" :xl="6"
                    ><dd>
                      结束时间：<span>{{ item.end_time ? item.end_time : '-' }}</span>
                    </dd></el-col
                  >
                </el-row>
              </dl>
            </el-col>
            <el-col :span="6" class="list_item_r">
              <el-button size="mini" type="primary" @click="detail(item.batch)">查看详情</el-button>
              <el-button size="mini" @click="exportFile(item)">下载</el-button>
              <el-button size="mini" v-if="item.run_sts == '2'" type="primary" plain @click="detailHref(item)">进入任务</el-button>
              <el-button size="mini" v-if="item.run_sts == '1' || item.run_sts == '2'" type="danger" plain @click="endTask(item)">终止任务</el-button>
            </el-col>
          </el-row>
        </li>
      </ul>
      <div v-else class="noData"></div>
      <el-pagination
        small
        background
        :current-page="pageIndex"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalPage"
        @current-change="currentChangeHandle"
        @size-change="sizeChangeHandle"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; text-align: right"
      ></el-pagination>
    </div>
    <el-dialog :title="detailTitle" :visible.sync="detailVisible" width="60%" :before-close="handleClose" :destroy-on-close="true">
      <div>
        <!--搜索-->
        <searchui :searchFormArr="searchFormArrDetail" @searchParma="searchDetailParma" :isAccording="isAccording" ref="child"></searchui>
        <div class="detailTable">
          <el-table :data="detailInfo" size="mini" :header-cell-style="{ background: '#F5F5F5', color: '#000000' }" ref="table" style="width: 100%" v-loading="dataListLoading" :row-class-name="tableRowClassName">
            <!-- <el-table-column align="center" header-align="center" label="通话记录ID" prop="ai_instance_id" width="120"></el-table-column> -->
            <el-table-column align="center" header-align="center" label="客户名称" prop="company_boss" width="150"></el-table-column>
            <el-table-column align="center" header-align="center" label="通话轮次" prop="talk_times" width="100"></el-table-column>
            <el-table-column align="center" header-align="center" label="意向标签" prop="talk_sts" width="100"></el-table-column>
            <el-table-column align="center" header-align="center" label="联系方式" prop="company_phone" width="120"></el-table-column>
            <el-table-column align="center" header-align="center" label="公司" prop="company_name" width="150"></el-table-column>
            <el-table-column align="center" header-align="center" label="归属地" prop="phone_address" width="150"></el-table-column>
            <el-table-column align="center" header-align="center" label="通话开始时间" prop="talk_start_time" width="150"></el-table-column>
            <el-table-column align="center" header-align="center" label="通话结束时间" prop="talk_end_time" width="150"></el-table-column>
            <el-table-column align="center" header-align="center" label="客户类型" prop="customer_type" width="100">
              <template slot-scope="scope">
                <span v-if="scope.row.customer_type == 1">普通</span>
                <span v-else-if="scope.row.customer_type == 2">意向</span>
              </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" header-align="center" label="操作" width="100">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="aiTalkRecord(scope.row)">查看录音</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            small
            background
            :current-page="detailPageIndex"
            :page-size="detailPageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="detailTotalPage"
            @current-change="currentChangeDetailHandle"
            @size-change="sizeChangeDetailHandle"
            layout="total, sizes, prev, pager, next, jumper"
            style="margin-top: 20px; text-align: right"
          ></el-pagination>
        </div>
      </div>
    </el-dialog>
    <!--编辑外呼任务-->
    <el-dialog title="编辑外呼任务" :visible.sync="outboundCallVisible" width="50%">
      <el-form size="mini" :model="form" :rules="rules" ref="form">
        <el-form-item label="外呼任务标题" :label-width="formLabelWidth" prop="title">
          <el-input v-model="form.title" autocomplete="off" maxlength="20" show-word-limit placeholder="请输入外呼任务标题"></el-input>
        </el-form-item>
        <el-form-item label="话术模板" :label-width="formLabelWidth" prop="robotDefId">
          <el-select v-model="form.robotDefId" placeholder="请选择话术模板">
            <el-option v-for="item in AITemplate" :key="item.robotDefId" :label="item.name" :value="item.robotDefId"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务开始时间" :label-width="formLabelWidth" prop="start_time">
          <el-date-picker v-model="form.start_time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间"> </el-date-picker>
        </el-form-item>
        <el-form-item label="任务坐席数" :label-width="formLabelWidth" prop="site_num">
          <el-input-number v-model="form.site_num" controls-position="right" :min="1" :step="1" :precision="0" :controls="false" :max="AIMax" :placeholder="AIzxPl"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="outboundCallReset('form')">取 消</el-button>
        <el-button size="mini" type="primary" @click="outboundCallSubmit('form')" :disabled="disabled">确 定</el-button>
      </div>
    </el-dialog>
    <!--  Ai外呼记录-->
    <el-dialog title="记录" :visible.sync="AIVisible" :destroy-on-close="true" @close="dialogAiClose">
      <div class="AIinfo">
        <audio :src="Aiinfo.talk_mp3" controls ref="audio"></audio>
        <template v-if="Aiinfo.content && Aiinfo.content.length > 0">
          <ul v-for="(item, index) in Aiinfo.content" :key="index">
            <li :style="item.speaker == 'ME' ? 'text-align:right' : ''">{{ item.content }}</li>
          </ul>
        </template>
        <el-empty v-else description="暂无数据" :image-size="150"></el-empty>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { AIBaseInfoApi, AITasksEditApi, endTask, AITasksInfoApi, AITasksListApi, apiSaveToExcel } from '@/api/outboundCall'
import { ai_talk_record } from '@/api/customer'

export default {
  name: 'index',
  data() {
    return {
      searchFormArr: [
        {
          fieldName: '',
          type: 'select',
          field: 'run_sts',
          option: [
            { id: '1', text: '待开始' },
            { id: '2', text: '进行中' },
            { id: '3', text: '已结束' },
            { id: '4', text: '已终止' },
            // { id: "4", text: "已删除" }
          ],
          placeholder: '请选择状态',
        },
        {
          fieldName: '外呼类型',
          type: 'select',
          field: 'run_type',
          option: [
            { id: 1, text: '资产' },
            { id: 2, text: '回收' },
            { id: 3, text: '造粒厂' },
            { id: 4, text: '制品厂' },
            { id: 5, text: '智能' },
            { id: 6, text: '名录' },
          ],
          placeholder: '请选择外呼类型',
          width: 180,
        },
        {
          fieldName: '创建时间',
          type: 'timePicker',
          field: 'time',
          placeholder: '请选择创建时间',
          timeType: 'daterange',
          format: 'yyyy-MM-dd',
        },
        {
          fieldName: '',
          type: 'inputSearch',
          field: 'title',
          placeholder: '请输入内容',
        },
      ],
      isAccording: true,
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataList: [],
      searchParams: {
        title: '',
        run_sts: '',
        start_time: '',
        end_time: '',
        run_type: '',
      },
      //详情
      detailVisible: false,
      detailTitle: '任务名称',
      searchFormArrDetail: [
        {
          fieldName: '时间选择',
          type: 'timePicker',
          field: 'time',
          placeholder: '请选择时间',
          timeType: 'daterange',
          format: 'yyyy-MM-dd',
        },
        {
          fieldName: '',
          type: 'select',
          field: 'talk_sts',
          option: [
            { id: 'A', text: 'A' },
            { id: 'B', text: 'B' },
            { id: 'C', text: 'C' },
            { id: 'D', text: 'D' },
            { id: 'E', text: 'E' },
            { id: 'F', text: 'F' },
          ],
          placeholder: '请选择意向标签',
          multiple: true,
        },
        {
          fieldName: '',
          type: 'select',
          field: 'talk_times',
          option: [
            { id: '10以上', text: '10以上' },
            { id: '10', text: '10' },
            { id: '9', text: '9' },
            { id: '8', text: '8' },
            { id: '7', text: '7' },
            { id: '6', text: '6' },
            { id: '5', text: '5' },
            { id: '4', text: '4' },
            { id: '3', text: '3' },
            { id: '2', text: '2' },
            { id: '1', text: '1' },
            { id: '0', text: '0' },
          ],
          placeholder: '请选择通话轮次',
          multiple: true,
          width: 180,
        },
        {
          fieldName: '',
          type: 'inputSearch',
          field: 'title',
          placeholder: '请输入搜索的用户号码',
        },
      ],
      detailPageIndex: 1,
      detailPageSize: 10,
      detailTotalPage: 0,
      detailInfo: [],
      detailId: '',
      datailTitle: '',
      searchDetailParams: {
        title: '',
        talk_sts: '',
        talk_times: '',
        start_time: '',
        end_time: '',
      },
      // AI外呼
      outboundCallVisible: false,
      form: {
        title: '',
        robotDefId: '',
        start_time: '',
        site_num: undefined,
      },
      formLabelWidth: '120px',
      rules: {
        title: [{ required: true, message: '请输入任务标题', trigger: 'blur' }],
        robotDefId: [{ required: true, message: '请选择话术模板', trigger: 'change' }],
        start_time: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
      },
      AITemplate: [],
      AIMax: 1,
      AIzxPl: '任务最大坐席数为1',
      disabled: false,
      AIVisible: false, //Ai外呼记录弹出层
      Aiinfo: {}, //AI外呼记录详情
    }
  },
  created() {
    this.setSearchDetailParma()
  },
  mounted() {
    this.getAITasksList()
    this.getAITempalteAll()
  },
  methods: {
    // 列表查询
    searchParma(e) {
      if (e.title) {
        this.searchParams.title = e.title
      } else {
        this.searchParams.title = ''
      }
      if (e.run_sts) {
        this.searchParams.run_sts = e.run_sts
      } else {
        this.searchParams.run_sts = ''
      }
      if (e.run_type) {
        this.searchParams.run_type = e.run_type
      } else {
        this.searchParams.run_type = ''
      }
      if (e.time[0]) {
        this.searchParams.start_time = e.time[0]
        this.searchParams.end_time = e.time[1]
      } else {
        this.searchParams.start_time = ''
        this.searchParams.end_time = ''
      }
      this.pageIndex = 1
      this.getAITasksList()
    },
    // 获取短信列表
    getAITasksList() {
      this.dataListLoading = true
      const info = Object.assign({ pageNumber: this.pageIndex, pageSize: this.pageSize }, this.searchParams)
      const formData = new FormData()
      for (let key in info) {
        formData.set(key, info[key])
      }
      AITasksListApi(formData)
        .then((res) => {
          this.dataList = res.result.items
          this.totalPage = res.result.total
          this.dataListLoading = false
        })
        .catch((e) => {
          this.dataList = []
          this.totalPage = 0
          this.dataListLoading = false
        })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getAITasksList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getAITasksList()
    },
    // 查看详情
    detail(batch) {
      if (batch) {
        this.$router.push({
          name: 'OutCallFlow',
          query: {
            batch,
          },
        })
      }
    },
    AITasksInfo() {
      const info = Object.assign({ batch: this.detailId, pageNumber: this.detailPageIndex, pageSize: this.detailPageSize }, this.searchDetailParams)
      const formData = new FormData()
      for (let key in info) {
        formData.set(key, info[key])
      }
      AITasksInfoApi(formData)
        .then((res) => {
          this.detailVisible = true
          this.detailTitle = '任务名称【' + this.datailTitle + '】'
          this.detailInfo = res.result.items
          this.detailTotalPage = res.result.total
        })
        .catch((e) => {
          this.detailVisible = false
          this.detailTitle = '任务名称'
          this.detailInfo = []
          this.detailTotalPage = 0
        })
    },
    // 设置日期筛选默认今天
    setSearchDetailParma() {
      const today = new Date()
      const todayFormat = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`
      this.searchFormArrDetail[0].default = [todayFormat, todayFormat]
      this.searchDetailParams.start_time = todayFormat
      this.searchDetailParams.end_time = todayFormat
    },
    // 详情查询
    searchDetailParma(e) {
      if (e.title) {
        this.searchDetailParams.title = e.title
      } else {
        this.searchDetailParams.title = ''
      }
      if (e.time) {
        this.searchDetailParams.start_time = e.time[0]
        this.searchDetailParams.end_time = e.time[1]
      } else {
        this.searchDetailParams.start_time = ''
        this.searchDetailParams.end_time = ''
      }
      if (e.talk_sts) {
        this.searchDetailParams.talk_sts = e.talk_sts
      } else {
        this.searchDetailParams.talk_sts = ''
      }
      if (e.talk_times) {
        this.searchDetailParams.talk_times = e.talk_times
      } else {
        this.searchDetailParams.talk_times = ''
      }
      this.detailPageIndex = 1
      this.AITasksInfo()
    },
    // 每页数
    sizeChangeDetailHandle(val) {
      this.detailPageSize = val
      this.detailPageIndex = 1
      this.AITasksInfo()
    },
    // 当前页
    currentChangeDetailHandle(val) {
      this.detailPageIndex = val
      this.AITasksInfo()
    },
    handleClose() {
      this.detailVisible = false
      this.detailInfo = []
      this.detailTotalPage = 0
      this.detailPageIndex = 1
      this.detailId = ''
      this.datailTitle = ''
      this.searchDetailParams.title = ''
      this.searchDetailParams.talk_sts = ''
      this.searchDetailParams.task_sts = ''
      this.$refs.child.resetFormClose()
    },
    //进入任务
    detailHref(item) {
      this.$router.push({
        name: 'OutCallManagerDetail',
        query: {
          title: item.title,
          batch: item.batch,
        },
      })
    },
    endTask(item) {
      this.$confirm('任务终止后不可恢复，确认终止任务吗?', '提示', {
        type: 'warning',
      })
        .then(() => {
          const formData = new FormData()
          formData.set('id', item.id)
          endTask(formData).then((res) => {
            if (res.code == 200) {
              this.$message.success('终止成功')
              this.getAITasksList()
            }
          })
        })
        .catch(() => {})
    },
    //编辑
    edit(item) {
      this.form.id = item.id
      this.form.title = item.title
      this.form.robotDefId = item.robotDefId
      this.form.start_time = item.start_time
      this.form.site_num = item.site_num
      this.outboundCallVisible = true
    },
    // 下载
    exportFile(item) {
      const formData = new FormData()
      formData.set('batch', item.batch)
      apiSaveToExcel(formData).then((res) => {
        let blob = new Blob([res], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        })
        let url = window.URL.createObjectURL(blob)
        this.download(url, item.title + '.xls')
      })
    },
    // 下载文件
    download(blobUrl, name) {
      const a = document.createElement('a')
      a.style.displav = 'none'
      a.download = name
      a.href = blobUrl
      a.click()
    },
    // 获取所有话术模板
    getAITempalteAll() {
      AIBaseInfoApi()
        .then((res) => {
          this.AITemplate = res.data.talk_words
          //任务坐席最大数
          this.AIMax = res.data.max_site_num
          this.AIzxPl = '任务最大坐席数为' + res.data.max_site_num
        })
        .catch((e) => {
          this.AITemplate = []
        })
    },
    //新建外呼任务提交
    outboundCallSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.disabled = true
          const info = Object.assign(this.form)
          const formData = new FormData()
          for (let key in info) {
            formData.set(key, info[key])
          }
          AITasksEditApi(formData)
            .then((res) => {
              this.outboundCallReset('form')
              this.$message({
                message: '编辑外呼任务成功',
                type: 'success',
              })
            })
            .catch((e) => {
              setTimeout(() => {
                this.disabled = false
              }, 2000)
            })
        } else {
          return false
        }
      })
    },
    //取消
    outboundCallReset(formName) {
      this.$refs[formName].resetFields()
      this.outboundCallVisible = false
    },
    // 表格标注颜色：如果 talk times > 2 and status = 1 标注其他颜色else 默认色
    tableRowClassName({ row, rowIndex }) {
      if (row.talk_times > 2 && row.status === 1) {
        return 'high-light'
      }
      return ''
    },
    // ai外呼记录
    aiTalkRecord(data) {
      this.Aiinfo = {}
      this.AIVisible = true
      ai_talk_record({ id: data.id }).then((res) => {
        this.Aiinfo = res.data
      })
    },
    // 关闭ai外呼记录，更新列表
    dialogAiClose() {
      this.AITasksInfo()
    },
  },
}
</script>

<style scoped lang="scss">
.searchContent {
  width: 100%;
  background: #fff;
  padding: 12px 16px;
  box-sizing: border-box;
}
.finishedColor {
  color: #fc151e !important;
}
.delColor {
  color: #979699 !important;
}
.container {
  padding: 16px;
  box-sizing: border-box;
  background: #f0f1f4;
  .conBlock {
    width: 100%;
    background: #fff;
    margin-top: 10px;
    padding: 12px 16px;
    box-sizing: border-box;
    .list_content {
      padding: 0;
      .list_item {
        border: 1px solid #e2e2e2;
        border-radius: 4px;
        padding: 12px 16px;
        box-sizing: border-box;
        width: 100%;
        margin-bottom: 24px;
        list-style: none;
        &:last-child {
          margin-bottom: 0;
        }
        .list_item_l {
          margin: 0;
          dt {
            margin: 0 0 20px;
            font-size: 14px;
            .status {
              margin-right: 20px;
              color: #2ca81d;
            }
          }
          dd {
            display: inline-block;
            margin: 12px 0;
            color: #8c8c8c;
            span {
              vertical-align: text-top;
              color: #262626;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
            }
          }
        }
        .list_item_r {
          display: flex;
          flex-direction: column;
          align-items: flex-end;
          button {
            display: block;
            width: 98px;
            margin: 0 0 5px 0;
            &:last-child {
              margin: 0px;
            }
          }
        }
      }
    }
  }
  .noData {
    display: block;
    width: 150px;
    height: 100px;
    background: url('../../../assets/img/noData.png') no-repeat;
    color: #909399;
    box-sizing: border-box;
    margin: 50px auto 0;
  }
}
.detailTable {
  margin-top: 4px;
}
.el-date-editor.el-input,
.el-input-number,
.el-select {
  width: 100%;
}
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
::v-deep .delayBlock .el-form-item__content {
  display: flex;
}
::v-deep .delayBlock .el-form-item__content .el-input-number {
  margin: 0 20px;
}
::v-deep .high-light {
  background: #e1eefc;
}
.AIinfo {
  text-align: center;
  height: 400px;
  overflow: auto;
}
.AIinfo audio {
  width: 100%;
}
.AIinfo ul {
  list-style: none;
  padding: 0 10px;
  box-sizing: border-box;
}
.AIinfo ul li {
  text-align: left;
  line-height: 1.7em;
}

::v-deep .el-form--inline .el-form-item {
  margin-bottom: 10px;
}
</style>
